import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_learning/charts/app_colors.dart';
import 'package:flutter_learning/utils/ly_app_color.dart';

class LYBarChartData {
  String? title;
  List<LYBarChartRodData> rodDataList;

  LYBarChartData({this.title, required this.rodDataList});
}

class LYBarChartRodData {
  double toY;
  Color? color;
  LYBarChartRodData({required this.toY, this.color});
}

class LYBarChartView extends StatefulWidget {
  final List<LYBarChartData>? chartDataItems;
  final String title;
  final String? hexColor;
  final Function(int)? clickCallBack;
  const LYBarChartView(
      {Key? key, required this.title, this.chartDataItems, this.hexColor, this.clickCallBack})
      : super(key: key);
  @override
  State<LYBarChartView> createState() => _LYBarChartViewState();
}

class _LYBarChartViewState extends State<LYBarChartView> {
  final double barWidth = 20;
  final List<BarChartGroupData> _barGroups = [];
  late FlTitlesData _titlesData;
  String _hexColor = '8cb2ff';
  late LinearGradient _barsGradient;

  @override
  void initState() {
    super.initState();
    if (widget.hexColor != null) {
      _hexColor = widget.hexColor!;
    }
    _barsGradient = LinearGradient(
      colors: [
        HexColor("FF$_hexColor"),
        HexColor("88$_hexColor"),
      ],
      begin: Alignment.bottomCenter,
      end: Alignment.topCenter,
    );
  }

  @override
  Widget build(BuildContext context) {
    _makeBarGroupsData();
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.only(left: 25, top: 0, bottom: 30),
          child: Text(
            widget.title,
            style: const TextStyle(fontSize: 15, color: AppColor.color333333),
          ),
        ),
        Expanded(
          child: BarChart(
            BarChartData(
              barTouchData: barTouchData,
              titlesData: _titlesData,
              borderData: borderData,
              barGroups: _barGroups,
              // maxY: _maxYValue.toDouble(),
              gridData: FlGridData(
                  show: true,
                  drawHorizontalLine: true,
                  drawVerticalLine: false,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(
                      color: AppColor.color666666,
                      strokeWidth: 0.5,
                    );
                  }),
              alignment: BarChartAlignment.spaceAround,
            ),
          ),
        ),
      ],
    );
  }

  BarTouchData get barTouchData => BarTouchData(
        enabled: true,
        allowTouchBarBackDraw: true,
        touchCallback: (event, response) {
          if ((event is FlTapUpEvent) && (response is BarTouchResponse)) {
            if (widget.clickCallBack != null && response.spot != null) {
              widget.clickCallBack!(response.spot!.touchedBarGroupIndex);
            }
          }
        },
        touchTooltipData: BarTouchTooltipData(
          // tooltipBgColor: Colors.transparent,
          getTooltipColor: (group) => Colors.transparent,
          tooltipPadding: const EdgeInsets.symmetric(horizontal: 10),
          tooltipMargin: 8,
          getTooltipItem: (
            BarChartGroupData group,
            int groupIndex,
            BarChartRodData rod,
            int rodIndex,
          ) {
            return BarTooltipItem(
              rod.toY.round().toString(),
              TextStyle(
                color: HexColor("ff$_hexColor"),
                fontWeight: FontWeight.normal,
              ),
            );
          },
        ),
      );

  FlBorderData get borderData => FlBorderData(
        show: false,
      );

  void _makeBarGroupsData() {
    _barGroups.clear();
    final items = widget.chartDataItems;
    if (items != null && items.isNotEmpty) {
      for (int index = 0; index < items.length; index++) {
        final model = items[index];
        final barRods = model.rodDataList.map((e) => _makeChartRodData(e)).toList();
        final itemData = BarChartGroupData(
          x: index,
          barRods: barRods,
          showingTooltipIndicators: [0, 1],
        );
        _barGroups.add(itemData);
      }
    }
    _titlesData = FlTitlesData(
      show: true,
      bottomTitles: AxisTitles(
        sideTitles: SideTitles(
          showTitles: true,
          reservedSize: 30,
          getTitlesWidget: (value, meta) {
            final index = value.toInt();
            final model = widget.chartDataItems?[index];
            return SideTitleWidget(
              axisSide: meta.axisSide,
              space: 4.0,
              // angle: 0.1* pi,
              // fitInside: SideTitleFitInsideData.fromTitleMeta(meta),
              child: Text(model?.title ?? '',
                  style: const TextStyle(
                    color: AppColor.color666666,
                    fontSize: 12,
                  )),
            );
          },
        ),
      ),
      leftTitles: AxisTitles(
        sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 60,
            getTitlesWidget: (value, meta) {
              // _maxYValue = meta.appliedInterval + meta.max;
              if (value == meta.max) {
                return const SizedBox();
              }
              return Container(
                width: 60,
                alignment: Alignment.centerRight,
                child: Text(
                  meta.formattedValue,
                ),
              );
            }),
        drawBelowEverything: true,
      ),
      topTitles: const AxisTitles(
        sideTitles: SideTitles(showTitles: false),
      ),
      rightTitles: const AxisTitles(
        sideTitles: SideTitles(showTitles: false),
      ),
    );
  }

  BarChartRodData _makeChartRodData(LYBarChartRodData rod) {
    return BarChartRodData(
      toY: rod.toY,
      gradient: _barsGradient,
      width: barWidth,
      borderRadius: BorderRadius.zero,
    );
  }
}
